# added by yinchao, Mon June 24 17:21	2024
# 一个写二进制文件的示例, 通过 socket 从 network 上读取一个图片, 并且保存到文件.

import socket

mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysocket.connect(('data.pr4e.org', 80))
cmd = b'GET http://data.pr4e.org/cover3.jpg HTTP/1.0\r\n\r\n'
mysocket.sendall(cmd)

content = b''
# count = 0
while True:
    data = mysocket.recv(4096)
    if len(data) < 1:
        break

    # count += len(data)
    # print(len(data), count)
    content += data

mysocket.close()

pos = content.find(b'\r\n\r\n')
print('Header length', pos)
print(content[:pos].decode())
# print(content[:pos+4].decode())

# test = 'yinchao'
# print(test.find('c'))  # 3
# test = 'yincchao'
# print(test.find('cc'))  # 3, the lowest index.

content = content[pos+4:]
fhand = open('cover3.jpg', 'wb')
fhand.write(content)
fhand.close()
